836 - Largest submatrix (DP, programación dinámica, O(n^4) ¿Existirá un O(n^3)?)
[andmenj-acm.git] / 705 - Slash maze / 705.4.cpp
blob36a01c86fbadfd782bd6a942b0da76de9ab7550d
1 #include <iostream>
3 using namespace std;
5 int g[226][226];
6 bool visited[226][226];
8 int r, c;
9 bool cycle;
11 //#define DEBUG
13 typedef pair<int, int> node;
15 int di[] = { 0, +1, 0, -1};
16 int dj[] = {+1, 0, -1, 0};
18 int shoot(const node &u, const node &dad, const node &start){
20 int cuenta = 1;
21 int i = u.first, j = u.second;
23 visited[i][j] = true;
24 //printf("Shooting (%d,%d)\n", i, j);
25 bool probable = false;
26 for (int k=0; k<4; ++k){
27 int ni = i + di[k];
28 int nj = j + dj[k];
30 //printf(" Objetivo: (%d,%d)\n", ni, nj);
32 //printf("r y c son: %d, %d\n", r, c);
34 if (0 <= ni && ni < 3*r &&
35 0 <= nj && nj < 3*c &&
36 g[ni][nj] != -1){
38 if (!visited[ni][nj]){
39 cuenta += shoot(node(ni, nj), u, start);
40 }else if (node(ni, nj) == start && node(ni, nj) != dad){
41 probable = true;
45 if (probable && cuenta == 1){
46 cycle = true;
48 return cuenta;
52 int main(){
53 int mazeNo = 1;
54 while ( cin >> c >> r && r && c){
56 for (int i=0; i<3*r; ++i) for (int j=0; j<3*c; ++j){ visited[i][j] = g[i][j] = 0; }
58 for (int i=0; i<r; ++i){
59 for (int j=0; j<c; ++j){
60 char d;
61 cin >> d;
62 if (d == '\\'){
63 g[3*i][3*j] = g[3*i+1][3*j+1] = g[3*i+2][3*j+2] = -1;
64 }else if (d == '/'){
65 g[3*i][3*j+2] = g[3*i+1][3*j+1] = g[3*i+2][3*j] = -1;
71 #ifdef DEBUG
72 for (int i=0; i<3*r; ++i){
73 for (int j=0; j<3*c; ++j){
74 printf("%3d", g[i][j]);
76 cout << endl;
78 cout << endl;
79 #endif
81 int longest = -9999999;
83 int count = 0;
84 for (int i=0; i<3*r; ++i){
85 for (int j=0; j<3*c; ++j){
86 if (g[i][j] != -1 && !visited[i][j]){
88 //printf("Shooting (%d,%d)\n", i, j);
90 cycle = false;
91 int dist = shoot(node(i, j), node(-1,-1), node(i, j));
92 //cout << "Cycle of length " << dist << " found.\n";
93 if (cycle){
94 longest >?= dist;
95 ++count;
101 #ifdef DEBUG
102 for (int i=0; i<3*r; ++i){
103 for (int j=0; j<3*c; ++j){
104 printf("%3d", g[i][j]);
106 cout << endl;
108 cout << endl;
109 #endif
111 printf("Maze #%d:\n", mazeNo++);
112 if (count > 0){
113 printf("%d Cycles; the longest has length %d.\n", count, longest/3);
114 }else{
115 printf("There are no cycles.\n");
118 cout << endl;
120 return 0;